package main

import (
	"fmt"
	"os"
	"time"

	"github.com/faiface/beep"
	"github.com/faiface/beep/wav"
	"github.com/faiface/beep/speaker"
)

func main() {
	err := playAudio("alarm.wav")
	if err != nil {
		fmt.Println("播放失败:", err)
	}
}

func playAudio(filename string) error {
	f, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("打开音频文件失败: %w", err)
	}
	defer f.Close()

	// 解码 MP3
	streamer, format, err := wav.Decode(f)
	if err != nil {
		return fmt.Errorf("音频解码失败: %w", err)
	}
	defer streamer.Close()

	// 初始化 speaker（根据采样率设置缓冲区大小）
	err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
	if err != nil {
		return fmt.Errorf("初始化音频输出失败: %w", err)
	}

	// 播放
	done := make(chan bool)
	speaker.Play(beep.Seq(streamer, beep.Callback(func() {
		done <- true
	})))

	<-done // 等待播放完成
	return nil
}
